﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrmApplication.Models;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;


namespace CrmApplication.Controllers
{
    public class MailerController : Controller
    {
        //
        // GET: /Mailer/

        public ActionResult Index()
        {
            return View();
        }

		/// <summary>
		/// select all mailers from database
		/// </summary>
		/// <returns></returns>
		public ActionResult GetMailer ()
		{
			MailerContainer container = MailerModels.GetMailerArray();
			return Json(container, JsonRequestBehavior.AllowGet);
		}

		[ValidateInput(false)]
		public ActionResult GetMailerById ()
		{
			decimal idMailer = 0;
			Decimal.TryParse(Request.Params["Id"], out idMailer);

			MailerContainer container = MailerModels.GetMailerArrayById(idMailer);

			return Json(container, JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// add/modify mailer infos
		/// </summary>
		/// <returns></returns>
		//[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult EditMailer ()
		{
			decimal idMailer = 0;
			Decimal.TryParse(Request.Params["Id"], out idMailer);
			decimal idCampaign = 0;
			Decimal.TryParse(Request.Params["IdCampaign"], out idCampaign);
			decimal status = 0;
			Decimal.TryParse(Request.Params["Status"], out status);
			DateTime date = new DateTime();
			DateTime.TryParse(Request.Params["StartDate"], out date);

			MailerModels mailer = new MailerModels();
			mailer.IdMailer = idMailer;
			mailer.IdCampaign = idCampaign;
			mailer.Status = status;
			mailer.MailerName = Request.Params["MailerName"];

			string bodyString = Request.Params["MailerBodyL"];
			byte[] byt = System.Text.Encoding.UTF8.GetBytes(bodyString);
			//string bodyString64 = Convert.ToBase64String(byt);
			mailer.MailerBody = byt;
			
			mailer.StartDate = date;

			string messageBack = null; ;

			try
			{
				if (idMailer == 0)
				{
					MailerModels.AddMailer(mailer);
					messageBack = "Mailer-ul a fost adaugat cu succes!";
				}
				else
					if (idMailer != 0)
					{
						MailerModels.EditMailer(mailer);
						messageBack = "Mailer-ul a fost modificat cu succes!";
					}
				return Json(new { success = true, description = messageBack });
			}
			catch (Exception ex)
			{
				if (ex.Message.Contains("unique key constraint"))
				{
					messageBack = "Exista deja o inregistrare cu acelasi nume!";
				}
				return Json(new { success = true, description = messageBack });
			}
		}

    }
}
